package freespiritsocial.io.user.ui.fragment.account

import android.graphics.Paint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgVerificationCodeBinding
import freespiritsocial.io.user.ext.goMain
import freespiritsocial.io.user.ext.setTitle
import freespiritsocial.io.user.handle.BackHandle
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.util.CountDownTimerHelper
import freespiritsocial.io.user.viewmodel.SignUpModel
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.nav

/**
 * 临时抽出一个忘记密码验证码
 * @property timerHelper CountDownTimerHelper
 */
class ForgotVerificationCodeFrg: BaseFragment<SignUpModel,FrgVerificationCodeBinding>() {
    private val timerHelper by lazy(LazyThreadSafetyMode.NONE) {
        CountDownTimerHelper(lifecycleScope,mViewModel.countDownTip)
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        view.setTitle(getString(R.string.code))
    }

    override fun layoutId(): Int = R.layout.frg_verification_code

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.phoneNumber.set(arguments?.getString("phoneNumber"))
        mViewModel.countryCode.set(arguments?.getString("countryCode"))
        mViewModel.password.set(arguments?.getString("password"))
        mDatabind.viewModel = mViewModel
        mDatabind.click = Click()
        mDatabind.tvCountdownTip.paintFlags = Paint.UNDERLINE_TEXT_FLAG
    }

    override fun lazyLoadData() {
        mViewModel.sendSmsCode(2)
        timerHelper.startCountDown()
    }

    override fun onDestroyView() {
        mViewModel.code.set("")
        timerHelper.cancel()
        super.onDestroyView()
    }


    inner class Click: VerificationCodeClick {
        override fun sendCode() {
            mViewModel.sendSmsCode(2)
            timerHelper.startCountDown()
        }

        override fun submit() {
            mViewModel.forget {
                CacheUtil.token = it
                nav().goMain()
            }
        }

        override fun goBack() {
            nav().navigateUp()
        }
    }
}